<template>
  <div class="app-container">
    <!-- 用户偏好设置卡片 -->
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold;">
          <i class="el-icon-setting"></i> 个人偏好设置
        </span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="handleReset">
          <i class="el-icon-refresh"></i> 重置为默认
        </el-button>
      </div>

      <el-form ref="preferenceForm" :model="form" :rules="rules" label-width="120px" v-loading="loading">
        <!-- 基础设置 -->
        <el-card class="setting-card" shadow="never">
          <div slot="header">
            <i class="el-icon-user"></i> 基础设置
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="界面主题" prop="theme">
                <el-select v-model="form.theme" placeholder="请选择界面主题" style="width: 100%">
                  <el-option label="浅色主题" value="light" />
                  <el-option label="深色主题" value="dark" />
                  <el-option label="自动切换" value="auto" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="语言设置" prop="language">
                <el-select v-model="form.language" placeholder="请选择语言" style="width: 100%">
                  <el-option label="简体中文" value="zh-CN" />
                  <el-option label="English" value="en-US" />
                  <el-option label="繁體中文" value="zh-TW" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="通知状态">
                <el-switch
                  v-model="form.notificationEnabled"
                  active-text="开启"
                  inactive-text="关闭"
                  active-value="1"
                  inactive-value="0">
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="活跃场景" prop="activeSceneId">
                <el-select v-model="form.activeSceneId" placeholder="请选择活跃场景" style="width: 100%" clearable>
                  <el-option
                    v-for="scene in sceneOptions"
                    :key="scene.sceneId"
                    :label="scene.sceneName"
                    :value="scene.sceneId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 舒适度范围设置 -->
        <el-card class="setting-card" shadow="never">
          <div slot="header">
            <i class="el-icon-data-analysis"></i> 舒适度范围设置
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="温度范围 (°C)" prop="comfortTempRange">
                <el-slider
                  v-model="form.comfortTempRange"
                  range
                  :min="10"
                  :max="35"
                  :step="0.5"
                  show-stops
                  :format-tooltip="formatTempTooltip"
                  style="margin: 0 20px;">
                </el-slider>
                <div class="range-display">
                  {{ form.comfortTempRange[0] }}°C - {{ form.comfortTempRange[1] }}°C
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="湿度范围 (%)" prop="comfortHumidityRange">
                <el-slider
                  v-model="form.comfortHumidityRange"
                  range
                  :min="20"
                  :max="80"
                  :step="5"
                  show-stops
                  :format-tooltip="formatHumidityTooltip"
                  style="margin: 0 20px;">
                </el-slider>
                <div class="range-display">
                  {{ form.comfortHumidityRange[0] }}% - {{ form.comfortHumidityRange[1] }}%
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="空气质量 (AQI)" prop="comfortAirQualityMax">
                <el-slider
                  v-model="form.comfortAirQualityMax"
                  :min="0"
                  :max="300"
                  :step="10"
                  show-stops
                  :format-tooltip="formatAqiTooltip"
                  style="margin: 0 20px;">
                </el-slider>
                <div class="range-display">
                  ≤ {{ form.comfortAirQualityMax }} AQI
                  <el-tag :type="getAqiTagType(form.comfortAirQualityMax)" size="mini" style="margin-left: 10px">
                    {{ getAqiLevel(form.comfortAirQualityMax) }}
                  </el-tag>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="气压范围 (hPa)" prop="comfortPressureRange">
                <el-slider
                  v-model="form.comfortPressureRange"
                  range
                  :min="980"
                  :max="1050"
                  :step="5"
                  show-stops
                  :format-tooltip="formatPressureTooltip"
                  style="margin: 0 20px;">
                </el-slider>
                <div class="range-display">
                  {{ form.comfortPressureRange[0] }}hPa - {{ form.comfortPressureRange[1] }}hPa
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="光照范围 (lux)" prop="comfortLightRange">
                <el-slider
                  v-model="form.comfortLightRange"
                  range
                  :min="0"
                  :max="2000"
                  :step="50"
                  show-stops
                  :format-tooltip="formatLightTooltip"
                  style="margin: 0 20px;">
                </el-slider>
                <div class="range-display">
                  {{ form.comfortLightRange[0] }}lux - {{ form.comfortLightRange[1] }}lux
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 操作按钮 -->
        <el-form-item style="text-align: center; margin-top: 30px;">
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            <i class="el-icon-check"></i> 保存设置
          </el-button>
          <el-button @click="cancel">
            <i class="el-icon-close"></i> 取消
          </el-button>
          <el-button type="info" @click="handleInit">
            <i class="el-icon-refresh-left"></i> 初始化设置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getCurrentUserPreference, updateCurrentUserPreference, initUserPreference } from "@/api/environment/preference";
import { listScene } from "@/api/environment/scene";

export default {
  name: "EnvPreference",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 提交按钮loading
      submitLoading: false,
      // 表单参数
      form: {
        theme: 'light',
        language: 'zh-CN',
        notificationEnabled: '1',
        activeSceneId: null,
        comfortTempRange: [18, 26],
        comfortHumidityRange: [40, 60],
        comfortAirQualityMax: 75,
        comfortPressureRange: [1000, 1030],
        comfortLightRange: [200, 800]
      },
      // 场景选项
      sceneOptions: [],
      // 表单校验
      rules: {
        theme: [
          { required: true, message: "界面主题不能为空", trigger: "change" }
        ],
        language: [
          { required: true, message: "语言设置不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getInfo();
    this.getSceneOptions();
  },
  methods: {
    /** 查询用户偏好设置详细 */
    getInfo() {
      this.loading = true;
      getCurrentUserPreference().then(response => {
        if (response.data) {
          this.form = {
            ...this.form,
            ...response.data,
            comfortTempRange: [response.data.comfortTempMin || 18, response.data.comfortTempMax || 26],
            comfortHumidityRange: [response.data.comfortHumidityMin || 40, response.data.comfortHumidityMax || 60],
            comfortPressureRange: [response.data.comfortPressureMin || 1000, response.data.comfortPressureMax || 1030],
            comfortLightRange: [response.data.comfortLightMin || 200, response.data.comfortLightMax || 800]
          };
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 获取场景选项 */
    getSceneOptions() {
      listScene({}).then(response => {
        this.sceneOptions = response.rows || [];
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["preferenceForm"].validate(valid => {
        if (valid) {
          this.submitLoading = true;
          const submitData = {
            ...this.form,
            comfortTempMin: this.form.comfortTempRange[0],
            comfortTempMax: this.form.comfortTempRange[1],
            comfortHumidityMin: this.form.comfortHumidityRange[0],
            comfortHumidityMax: this.form.comfortHumidityRange[1],
            comfortPressureMin: this.form.comfortPressureRange[0],
            comfortPressureMax: this.form.comfortPressureRange[1],
            comfortLightMin: this.form.comfortLightRange[0],
            comfortLightMax: this.form.comfortLightRange[1]
          };
          
          updateCurrentUserPreference(submitData).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.submitLoading = false;
          }).catch(() => {
            this.submitLoading = false;
          });
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.getInfo();
    },
    /** 重置为默认 */
    handleReset() {
      this.$modal.confirm('确认重置为默认设置吗？').then(() => {
        this.form = {
          theme: 'light',
          language: 'zh-CN',
          notificationEnabled: '1',
          activeSceneId: null,
          comfortTempRange: [18, 26],
          comfortHumidityRange: [40, 60],
          comfortAirQualityMax: 75,
          comfortPressureRange: [1000, 1030],
          comfortLightRange: [200, 800]
        };
        this.$modal.msgSuccess("已重置为默认设置");
      });
    },
    /** 初始化设置 */
    handleInit() {
      this.$modal.confirm('确认初始化偏好设置吗？').then(() => {
        initUserPreference().then(response => {
          this.$modal.msgSuccess("初始化成功");
          this.getInfo();
        });
      });
    },
    // 格式化提示文本
    formatTempTooltip(val) {
      return val + '°C';
    },
    formatHumidityTooltip(val) {
      return val + '%';
    },
    formatAqiTooltip(val) {
      return val + ' AQI';
    },
    formatPressureTooltip(val) {
      return val + 'hPa';
    },
    formatLightTooltip(val) {
      return val + 'lux';
    },
    // 获取AQI等级
    getAqiLevel(aqi) {
      if (aqi <= 50) return '优';
      if (aqi <= 100) return '良';
      if (aqi <= 150) return '轻度污染';
      if (aqi <= 200) return '中度污染';
      if (aqi <= 300) return '重度污染';
      return '严重污染';
    },
    // 获取AQI标签类型
    getAqiTagType(aqi) {
      if (aqi <= 50) return 'success';
      if (aqi <= 100) return '';
      if (aqi <= 150) return 'warning';
      return 'danger';
    }
  }
};
</script>

<style scoped>
.setting-card {
  margin-bottom: 20px;
}

.setting-card .el-card__header {
  padding: 15px 20px;
  background-color: #f5f7fa;
  font-weight: bold;
}

.range-display {
  text-align: center;
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}

.box-card {
  margin-bottom: 20px;
}

.el-slider {
  margin: 20px 0;
}
</style>